$(function(){
  // 封装获取历史记录方法
  function getHistory(){
    var history = localStorage.getItem("history");
    history = JSON.parse(history) ||[] ;
    return history;
  }
  // 封装渲染方法
  function render(){
    var history = getHistory();
    $(".search_history").html(template("tmp",{list:history}));
  }

  render();

  // 删除功能
  $(".search_history").on("click",".icon_delete",function(){
    mui.confirm('确定要删除这条记录?','温馨提示',['是','否'],function(e){
      if(!e.index){
        // 取
        var history = getHistory();
        console.log(history);
        // 删
        var index = $(this).data("index");
        history.splice(index,1);
        history = JSON.stringify(history);
        console.log(history);
        // 存
        localStorage.setItem("history",history)
        // 重新渲染
        render();
      }
      
    })
  })
  // 清空历史记录
  $(".search_history").on("click",".icon_deleteAll",function(){
    mui.confirm('确定要清空记录?','温馨提示',['是','否'],function(e){
      if(!e.index){
        localStorage.removeItem("history");
        render();
      }
    })
  })

  $(".search_box button").on("click",function(){
    var value = $(".search_box input").val().trim();
    console.log(value);
    if(!value){
      mui.toast('请输入关键字') ;
      return;
    }
    var history = getHistory();
    var idx = history.indexOf(value);
    if(idx != -1){
      history.splice(idx,1);
    }
    if(history.length>=10){
      history.pop();
    }
    history.unshift(value);
    localStorage.setItem("history",JSON.stringify(history));
    render();
    // 页面跳转
    location.href = "searchList.html?key="+value;
    
  })

  

})